<template>
  <div class="page-container">
    <h1 class="page-title">录音管理</h1>
    
    <el-card shadow="hover">
      <div class="filter-container" style="display: flex; align-items: center; justify-content: space-between;">
        <div style="flex: 1; display: flex; align-items: center;">
          <el-input
            placeholder="搜索用户名/句子内容"
            v-model="searchQuery"
            style="width: 300px;"
            clearable
            @keyup.enter.native="handleSearch"
          >
            <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
          </el-input>
        </div>
        <el-button type="primary" @click="showExportDialog" style="margin-left: 20px; height: 48px; min-width: 160px; font-size: 20px; font-weight: bold; letter-spacing: 2px; display: flex; align-items: center; justify-content: center;">
          <i class="el-icon-download" style="font-size: 26px; margin-right: 10px;"></i> 导出录音
        </el-button>
      </div>
      
      <el-table
        :data="recordings"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="username" label="用户名" width="120"></el-table-column>
        <el-table-column prop="sentence_content" label="句子内容"></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="exportSingleRecording(scope.row)"
              plain
            >
              <i class="el-icon-download"></i> 导出
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              plain
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        >
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 导出录音对话框 -->
    <el-dialog title="导出录音" :visible.sync="exportVisible" width="400px">
      <div class="export-options">
        <el-radio-group v-model="exportType">
          <el-radio label="all">导出所有录音</el-radio>
          <el-radio label="user">按用户导出</el-radio>
          <el-radio label="sentence">按句子导出</el-radio>
        </el-radio-group>
        <div v-if="exportType === 'user'" style="margin-top: 20px;">
          <el-select v-model="selectedUserId" placeholder="请选择用户" filterable style="width: 100%;">
            <el-option v-for="user in userList" :key="user.id" :label="user.username" :value="user.id" />
          </el-select>
        </div>
        <div v-if="exportType === 'sentence'" style="margin-top: 20px;">
          <el-select v-model="selectedSentenceId" placeholder="请选择句子" filterable style="width: 100%;">
            <el-option v-for="sentence in sentenceList" :key="sentence.id" :label="sentence.content" :value="sentence.id" />
          </el-select>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exportVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmExport" :loading="exportLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Recordings',
  data() {
    return {
      recordings: [],
      loading: false,
      searchQuery: '',
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      exportVisible: false,
      exportType: 'all',
      exportLoading: false,
      userList: [],
      sentenceList: [],
      selectedUserId: '',
      selectedSentenceId: ''
    }
  },
  created() {
    this.fetchRecordings()
  },
  methods: {
    async fetchRecordings() {
      this.loading = true
      try {
        console.log('Recordings: 开始获取录音列表, 参数:', {
          page: this.pagination.currentPage,
          limit: this.pagination.pageSize,
          search: this.searchQuery
        })
        
        const params = {
          page: this.pagination.currentPage,
          limit: this.pagination.pageSize,
          search: this.searchQuery
        }
        
        const result = await this.$store.dispatch('fetchRecordings', params)
        console.log('Recordings: 录音列表获取成功:', result)
        
        // 检查数据结构并适配
        if (result && Array.isArray(result.items)) {
          this.recordings = result.items
          this.pagination.total = result.total
        } else if (result && Array.isArray(result.recordings)) {
          // 适配API文档中描述的数据结构
          this.recordings = result.recordings
          this.pagination.total = result.total
        } else if (Array.isArray(result)) {
          // 如果直接返回数组
          this.recordings = result
          this.pagination.total = result.length
        } else {
          console.error('未知的数据结构:', result)
          this.recordings = []
          this.pagination.total = 0
        }
      } catch (error) {
        console.error('Recordings: 获取录音列表失败:', error)
        this.$errorMessage('获取录音列表失败')
      } finally {
        this.loading = false
      }
    },
    
    handleSearch() {
      this.pagination.currentPage = 1
      this.fetchRecordings()
    },
    
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchRecordings()
    },
    
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchRecordings()
    },
    
    async handleDelete(row) {
      try {
        await this.$confirm('此操作将永久删除该录音，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        this.loading = true
        await this.$store.dispatch('deleteRecording', row.id)
        this.$successMessage('删除成功')
        this.fetchRecordings()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除录音失败:', error)
          this.$errorMessage('删除录音失败')
        }
      } finally {
        this.loading = false
      }
    },
    
    showExportDialog() {
      this.exportVisible = true
      this.exportType = 'all'
      this.selectedUserId = ''
      this.selectedSentenceId = ''
      // 弹窗打开时加载用户和句子列表
      this.fetchUserList()
      this.fetchSentenceList()
    },
    
    async fetchUserList() {
      try {
        const res = await this.$store.dispatch('fetchUsers', { page: 1, limit: 1000 })
        this.userList = Array.isArray(res.items) ? res.items : (res.users || res)
      } catch (e) {
        this.userList = []
      }
    },
    
    async fetchSentenceList() {
      try {
        const res = await this.$store.dispatch('fetchSentences', { page: 1, limit: 1000 })
        this.sentenceList = Array.isArray(res.items) ? res.items : (res.sentences || res)
      } catch (e) {
        this.sentenceList = []
      }
    },
    
    async confirmExport() {
      this.exportLoading = true
      try {
        let blob
        if (this.exportType === 'all') {
          blob = await this.$store.dispatch('exportAllRecordings')
        } else if (this.exportType === 'user') {
          if (!this.selectedUserId) {
            this.$errorMessage('请选择用户')
            this.exportLoading = false
            return
          }
          blob = await this.$store.dispatch('exportUserRecordings', this.selectedUserId)
        } else if (this.exportType === 'sentence') {
          if (!this.selectedSentenceId) {
            this.$errorMessage('请选择句子')
            this.exportLoading = false
            return
          }
          blob = await this.$store.dispatch('exportSentenceRecordings', this.selectedSentenceId)
        }
        if (blob) {
          const url = window.URL.createObjectURL(new Blob([blob]))
          let filename = 'recordings_export.zip'
          if (this.exportType === 'user') {
            const user = this.userList.find(u => u.id === this.selectedUserId)
            filename = `user_${user ? user.username : this.selectedUserId}_recordings.zip`
          } else if (this.exportType === 'sentence') {
            const sentence = this.sentenceList.find(s => s.id === this.selectedSentenceId)
            filename = `sentence_${sentence ? sentence.id : this.selectedSentenceId}_recordings.zip`
          }
          const link = document.createElement('a')
          link.href = url
          link.setAttribute('download', filename)
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          this.$successMessage('导出成功')
        }
      } catch (error) {
        console.error('Recordings: 导出失败:', error)
        this.$errorMessage('导出失败')
      } finally {
        this.exportLoading = false
        this.exportVisible = false
      }
    },

    async exportSingleRecording(row) {
      try {
        this.loading = true
        const response = await this.$store.dispatch('downloadRecording', row.id)
        
        if (response && response.blob) {
          // 处理句子内容，移除特殊字符并限制长度
          const sanitizedSentence = row.sentence_content
            .replace(/[\\/:*?"<>|]/g, '') // 移除Windows文件名中不允许的字符
            .replace(/\s+/g, '_') // 将空格替换为下划线
            .substring(0, 30) // 限制句子长度为30个字符
          
          const fileName = `${row.username}_${sanitizedSentence}.wav`
          
          const link = document.createElement('a')
          link.href = response.url
          link.setAttribute('download', fileName)
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          // 清理URL对象
          window.URL.revokeObjectURL(response.url)
          this.$successMessage('导出成功')
        } else {
          throw new Error('未收到有效的音频数据')
        }
      } catch (error) {
        console.error('导出单个录音失败:', error)
        this.$errorMessage('导出失败: ' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
  display: flex;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.export-options {
  padding: 20px;
}
</style> 